<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :width="600">
    <!-- 根据 isFormDisabled 控制表单禁用状态 -->
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()" :disabled="isFormDisabled">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!dataForm.id" label="密码" prop="password">
        <el-input v-model="dataForm.password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="dataForm.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="头像" prop="avatarUrl">
        <div v-if="!avatarFileList.length &&!dataForm.avatarUrl">
          <el-upload 
            :auto-upload="false"
            :on-change="handleAvatarChange"
            :show-file-list="false"
            list-type="picture-card"
            :disabled="isFormDisabled"
          >
            <img v-if="dataForm.avatarUrl" :src="dataForm.avatarUrl" class="avatar" style="width: 146px; height: 146px; border-radius: 5px" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
        <div v-else class="avatar-container" @mouseenter="!isFormDisabled && (showDeleteIcon = true)" @mouseleave="!isFormDisabled && (showDeleteIcon = false)">
          <img 
            :src="dataForm.avatarUrl || avatarFileList[0].url" 
            class="avatar" 
            style="width: 146px; height: 146px; border-radius: 5px"
          />
          <!-- 仅在表单启用时显示遮罩和删除图标 -->
          <div v-if="showDeleteIcon && !isFormDisabled" class="avatar-mask">
            <el-icon class="delete-icon" @click="handleAvatarRemove"><Delete /></el-icon>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="dataForm.role" placeholder="请选择角色" :disabled="isFormDisabled">
          <el-option
            v-for="item in props.roleMap"
            :key="item[0]"
            :label="item[1]"
            :value="`${item[0]}`"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="dataForm.status" placeholder="请选择状态" :disabled="isFormDisabled">
          <el-option
            v-for="item in props.statusMap"
            :key="item[0]"
            :label="item[1]"
            :value="`${item[0]}`"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <!-- 禁用操作按钮 -->
      <el-button @click="visible = false" :disabled="isFormDisabled">取消</el-button>
      <el-button type="primary" @click="submitHandle()" :disabled="isFormDisabled">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { ListVO } from '../data'
import { FormRules, type FormInstance } from 'element-plus'
import { add, update } from '../service'
import type { UploadProps, UploadFile } from 'element-plus' // 引入 UploadFile 类型
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue' // 引入删除图标
import { Http } from '@/network/request'

const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

const visible = ref(false)
const dataFormRef = ref<FormInstance>()

const dataForm = reactive<ListVO>({
  id: '',
  username: '',
  password: '',
  nickname: '',
  email: '',
  avatarUrl: '',
  role: '',
  status: '',
})

// 定义 avatarFileList 用于存储上传的文件列表
const avatarFileList = ref<UploadFile[]>([])
const showDeleteIcon = ref(false) // 控制删除图标显示隐藏

// 定义控制表单禁用状态的响应式变量
const isFormDisabled = ref(false)

const init = async (row?: ListVO) => {
  visible.value = true
  await nextTick()
  dataForm.id = ''

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
  }
  
  // 初始化时重置密码字段
  dataForm.password = ''

  if (row) {
    Object.assign(dataForm, row)
    // 修改时禁用表单
    isFormDisabled.value = true
  }else {
    // 新增时启用表单
    isFormDisabled.value = false
  }
    // 初始化时清空文件列表
  avatarFileList.value = []
}

const dataRules = reactive<FormRules<ListVO>>({
  username: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  password: [{ required: !dataForm.id, message: '必填项不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  avatarUrl: [{ required: true, message: '必填项不能为空', trigger: ['change', 'blur'] }],
  role: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
})

// 头像上传处理函数
const handleAvatarChange: UploadProps['onChange'] = async (uploadFile) => {
  try {
    const file = uploadFile.raw
    if (!file) return

    // 文件类型校验
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('仅支持 JPG/PNG/GIF/WEBP 格式')
      return
    }

    // 文件大小校验
    if (file.size > 1024 * 1024) {
      ElMessage.error('图片大小不能超过1MB')
      return
    }

    // 执行上传
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await Http.post('/file/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (res.code === 0 && res.data) {
      dataForm.avatarUrl = res.data as string
      // 手动触发表单验证
      await nextTick()
      dataFormRef.value?.validateField('avatarUrl')
    }
  } catch (error) {
    ElMessage.error('头像上传失败')
  }
}

// 删除文件回调
const handleAvatarRemove = () => {
  dataForm.avatarUrl = ''
  avatarFileList.value = []
  showDeleteIcon.value = false
}


// 表单提交
const submitHandle = () => {
  dataFormRef.value!.validate(async (valid) => {
    if (!valid) return

    let submitData = { ...dataForm };
    if (dataForm.id) {
      // 使用类型断言绕过类型检查
      delete (submitData as any).password; 
    }

    const res = dataForm.id ? await update(submitData) : await add(dataForm);
    if (res) {
      visible.value = false;
      emit('refreshDataList');
    }
  });
};

// 定义暴露的方法
defineExpose({
  init,
})

// 定义接收的props
const props = defineProps<{
  statusMap: Map<string, string>,
  roleMap: Map<string, string>,
}>()
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.avatar-container {
  position: relative;
  width: 146px;
  height: 146px;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-icon {
  color: white;
  font-size: 24px;
  cursor: pointer;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #CDD0D6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}

.delete-icon {
  color: white;
  font-size: 24px;
  cursor: pointer;
}

/* 禁用状态下的样式 */
.delete-icon.disabled {
  cursor: not-allowed;
  opacity: 0.5; /* 降低透明度，视觉上表示禁用 */
}

.delete-icon.disabled:hover::after {
  display: none; /* 移除悬停提示 */
}
</style>